<template>
  <div>
    <canvas ref="myCanvas" id="canvas" width="660" height="500"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import imagePath from '@/assets/erase/front.jpg?timestamp=${new Date().getTime()}';
const myCanvas = ref(null);
let isDrawing = false;
let ctx = null;

onMounted(() => {
  init();
  myCanvas.value.addEventListener('mousedown', onMouseDown);
})

function init() {
  const canvas = myCanvas.value;
  const ctx =canvas.getContext('2d');
  const image = new Image();
  image.src = imagePath;
  image.onload = function() {
    ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
    ctx.globalCompositeOperation = 'destination-out'
  };
}
function onMouseDown(event) {
  console.log("鼠标按下");
  const canvas = myCanvas.value;
  ctx = canvas.getContext('2d');

  ctx.beginPath();
  ctx.arc(event.offsetX, event.offsetY, 36, 0, 2 * Math.PI);
  ctx.fillStyle = 'red';
  ctx.fill();

  isDrawing = true;
  myCanvas.value.addEventListener('mousemove', onMouseMove);
  window.addEventListener('mouseup', onMouseUpHandler);
}

function onMouseMove(event) {
  if (isDrawing) {
    ctx.beginPath();
    ctx.moveTo(event.offsetX, event.offsetY);
    ctx.arc(event.offsetX, event.offsetY, 36, 0, 2 * Math.PI);
    ctx.lineWidth = 36;
    ctx.strokeStyle = 'red';
    ctx.stroke();

    // 检查是否需要清空灰色前景
    checkAndClearForeground(event.offsetX, event.offsetY);
  }
}

function onMouseUpHandler(event) {
  console.log("鼠标松开");
  isDrawing = false;
  myCanvas.value.removeEventListener('mousemove', onMouseMove);
  window.removeEventListener('mouseup', onMouseUpHandler);
}

function checkAndClearForeground(x, y) {
  const canvas = myCanvas.value;
  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  let validPixels = 0;

  for (let i = 0; i < imageData.data.length; i += 4) {
    const alpha = imageData.data[i + 3];
    if (alpha > 0) {
      validPixels++;
    }
  }

  const validPixelRatio = validPixels / (imageData.data.length / 4);

  if (validPixelRatio < 0.2) {
    ctx.fillStyle = 'gray';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
  }
}
</script>

<style scoped>
canvas {
  background-image: url('@/assets/erase/back.jpg');
  background-size: cover;
  background-position: center;
}
</style>
